package com.market.plus.core.aop;


import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

import com.market.plus.core.domain.Album;
import com.market.plus.core.domain.Avatar;
import com.market.plus.core.domain.Participant;
import com.market.plus.core.domain.Persistable;
import com.market.plus.core.domain.Status;
import com.market.plus.core.domain.Tribe;
import com.market.plus.core.util.MarketUtil;

@Aspect
public class UserAspect {

   @Before("execution(* com.market.plus.core.dao.GenericDao.save(..)) && args(persistable)")
   public void savePersistable(Object persistable) {
       if (persistable != null){
          setNewPersistableStatus(persistable);
       }
   }

   private void setModifyedUser(Object persistableObject, Status status, boolean allowedGuest){
      if (MarketUtil.hasAuthenticated())
         MarketUtil.setModifyedUser(persistableObject, status);
      else if (allowedGuest)
         MarketUtil.setGuestModifyedUser(persistableObject, status);
   }

   private void setNewPersistableStatus(Object persistableObject){
      Persistable persistable = (Persistable) persistableObject;
      Status status = Status.UPDATED;
      if (MarketUtil.hasIDNotExist(persistable.getId())){
         if (persistable instanceof Participant){
            Participant participant = (Participant) persistable;
            setModifyedUser(participant, status, true);

            Avatar avatar = participant.getAvatar();
            if (avatar != null){
               setModifyedUser(avatar, status, true);
            }

            Album album = participant.getAlbums().get(0);
            setModifyedUser(album, status, true);
         }if (persistable instanceof Tribe){
            Tribe tribe = (Tribe) persistable;
            setModifyedUser(tribe, status, false);

            Avatar avatar = tribe.getAvatar();
            if (avatar != null){
               setModifyedUser(avatar, status, false);
            }
         } else {
            setModifyedUser(persistableObject, status, false);
         }
      }
    }
}
